import minappSdk from "minapp-sdk"
import dayjs from "dayjs"
import { message } from "ant-design-vue"
import type { ResponsePromiseData } from "@/types"
import type { OralCaseItem } from "@/api/case/type"
import { getSearchHistory } from "./search"
import { SearchHistory } from "@/api/search/type"
// 表
const oralCaseTabel = new minappSdk.TableObject("Medifood_case")
const caseCollectionTabel = new minappSdk.TableObject("case_collection")
const oralCaseCategoryTabel = new minappSdk.TableObject("Medifood_case_classification")

// 获取闽南药膳分类(全部)
async function getAllCaseCategory<T>(): ResponsePromiseData<T> {
  let result: any = []
  let offset = 0
  while (true) {
    try {
      let res = await oralCaseCategoryTabel.limit(1000).offset(offset).find({ withCount: true })
      result = result.concat(res.data.objects)
      offset += 1000
      let total = res.data.meta.total_count
      if (result.length >= total) break
    } catch (error: any) {
      message.error(error.message)
      return Promise.reject(error.message)
    }
  }
  return { code: 0, data: result, message: "获取成功" }
}

// 获取闽南药膳分类(带分页)
async function getCaseCategoryList<T>(page: number = 1, pageSize: number = 10, searchQuery: any = null): ResponsePromiseData<T> {
  const offset: number = (page - 1) * pageSize
  let query = new minappSdk.Query()
  if (searchQuery?.constructor === Object) {
    for (let key in searchQuery) {
      query.contains(key, searchQuery[key]) //模糊搜索
      // query.compare(key, "=", searchQuery[key])
    }
  }
  try {
    const {
      data: {
        meta: { total_count },
        objects
      }
    } = await oralCaseCategoryTabel.setQuery(query).limit(pageSize).offset(offset).find({ withCount: true })

    return { code: 0, data: { list: objects, total: total_count } as T, message: "获取成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取闽南药膳分类详情
async function getCaseCategoryInfo<T>(id: string): ResponsePromiseData<T> {
  try {
    let { data } = await oralCaseCategoryTabel.get(id)
    return { code: 0, message: `获取成功`, data }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 更新闽南药膳分类
async function updateCateCategory(id: string, formState: any): ResponsePromiseData {
  try {
    let record = oralCaseCategoryTabel.getWithoutData(id)
    record.set({ ...formState })
    await record.update()
    return { code: 0, message: "更新成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 删除闽南药膳分类
async function deleteCaseCategory(id: string): ResponsePromiseData {
  try {
    await oralCaseCategoryTabel.delete(id)
    return { code: 0, message: "删除成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 新增闽南药膳分类
async function addCaseCategory(formState: any): ResponsePromiseData {
  let { data }: any = await getCaseRecords(1, 10, { name: formState.name })
  if (data.code == 0 && data.list.length) {
    throw new Error("分类已存在")
  }
  let MyRecord = oralCaseCategoryTabel.create()
  MyRecord.set(formState)
  try {
    await MyRecord.save()
    return { code: 0, message: "新增成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取闽南药膳(带分页)
async function getCaseRecords<T>(page: number = 1, pageSize: number = 10, searchQuery: any = null): ResponsePromiseData<T> {
  const offset: number = (page - 1) * pageSize
  let query: any = new minappSdk.Query()
  if (searchQuery?.constructor === Object) {
    for (let key in searchQuery) {
      // 如果 传入searchKey字段, 则查询所有字段，找出符合项
      if (key === "searchKey") {
        let query_name = new minappSdk.Query()
        query_name.contains("name", searchQuery.searchKey)
        let query_Medifood_recipe = new minappSdk.Query()
        query_Medifood_recipe.contains("Medifood_recipe", searchQuery.searchKey)
        let query_indication = new minappSdk.Query()
        query_indication.contains("indication", searchQuery.searchKey)
        let query_Medifood_aroma = new minappSdk.Query()
        query_Medifood_aroma.contains("Medifood_aroma", searchQuery.searchKey)
        let query_Medifood_usage = new minappSdk.Query()
        query_Medifood_usage.contains("Medifood_usage", searchQuery.searchKey)
        let query_treated_disease = new minappSdk.Query()
        query_treated_disease.contains("treated_disease", searchQuery.searchKey)
        let query_Medifood_color = new minappSdk.Query()
        query_Medifood_color.contains("Medifood_color", searchQuery.searchKey)
        let query_Medifood_flavor = new minappSdk.Query()
        query_Medifood_flavor.contains("Medifood_flavor", searchQuery.searchKey)
        let query_Associated_symptoms = new minappSdk.Query()
        query_Associated_symptoms.contains("Associated_symptoms", searchQuery.searchKey)
        let query_Edible_method = new minappSdk.Query()
        query_Edible_method.contains("Edible_method", searchQuery.searchKey)
        let query_treatment_site = new minappSdk.Query()
        query_treatment_site.contains("treatment_site", searchQuery.searchKey)

        query = minappSdk.Query.or(
          query_name,
          query_Medifood_recipe,
          query_indication,
          query_Medifood_aroma,
          query_Medifood_usage,
          query_treated_disease,
          query_Medifood_color,
          query_Medifood_flavor,
          query_Associated_symptoms,
          query_Edible_method,
          query_treatment_site
        )
      } else if (key === "advancedSearch") {
        let { data } = await getSearchHistory<SearchHistory>(searchQuery.advancedSearch)
        let queryInfo = JSON.parse(data!.search_query as unknown as string)
        // 目前只处理全并或全或的请求
        if (queryInfo.filter((item: any) => item.operator == "or").length > 0) {
          query = minappSdk.Query.or(
            ...queryInfo.map((item: any) => {
              let _query = new minappSdk.Query()
              return _query.contains(item.key, item.value)
            })
          )
        } else {
          query = minappSdk.Query.and(
            ...queryInfo.map((item: any) => {
              let _query = new minappSdk.Query()
              return _query.contains(item.key, item.value)
            })
          )
        }
      } else {
        query.compare(key, "=", searchQuery[key])
      }
    }
  }
  try {
    const {
      data: {
        meta: { total_count },
        objects
      }
    } = await oralCaseTabel.setQuery(query).limit(pageSize).offset(offset).find({ withCount: true })
    return {
      code: 0,
      message: `获取成功`,
      data: {
        list: objects,
        total: total_count
      } as T
    }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取闽南药膳详情
async function getCaseInfo<T>(id: string, user_id?: string): ResponsePromiseData<T> {
  try {
    let { data } = await oralCaseTabel.get(id)
    // 判断是否被当前用户收藏
    if (user_id) {
      // 先获取id
      let query: any = new minappSdk.Query()
      query.contains("user_id", user_id)
      query.contains("case_id", id)
      const {
        data: { objects }
      } = await caseCollectionTabel.setQuery(query).find()
      if (objects.length > 0) {
        data.isCollect = true
      }
    }

    return { code: 0, message: "获取成功", data }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 新增闽南药膳
async function addCaseRecord<T>(formState: OralCaseItem): ResponsePromiseData<T> {
  let MyRecord = oralCaseTabel.create()
  MyRecord.set(formState)
  try {
    await MyRecord.save()
    return { code: 0, message: "新增成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 更新闽南药膳
async function updateCaseRecord(id: string, formState: OralCaseItem): ResponsePromiseData {
  try {
    let record = oralCaseTabel.getWithoutData(id)
    record.set({ ...formState })
    await record.update()
    return { code: 0, message: "更新成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 删除闽南药膳
async function deleteCaseRecord(id: string): ResponsePromiseData {
  try {
    await oralCaseTabel.delete(id)
    return { code: 0, message: "删除成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取指定日期创建的药膳数量(默认当天)
async function getTodayCaseCount<T>(time: string = dayjs().format("YYYY-MM-DD")): ResponsePromiseData<T> {
  let query = new minappSdk.Query()
  try {
    query.contains("created_time", time)
    let {
      data: {
        meta: { total_count },
        objects
      }
    } = await oralCaseTabel.setQuery(query).find({ withCount: true })
    return { code: 0, data: { total: total_count, list: objects } as T, message: "获取成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 收藏药膳
async function collectCase(user_id: string, case_id: string): ResponsePromiseData {
  let MyRecord = caseCollectionTabel.create()
  MyRecord.set({
    user_id,
    case_id
  })
  try {
    await MyRecord.save()
    return { code: 0, message: "收藏成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 取消收藏药膳
async function unCollectCase(user_id: string, case_id: string): ResponsePromiseData {
  try {
    // 先获取id
    let query: any = new minappSdk.Query()
    query.contains("user_id", user_id)
    query.contains("case_id", case_id)
    const {
      data: { objects }
    } = await caseCollectionTabel.setQuery(query).find()
    if (!objects.length) throw new Error("取消收藏失败")
    // 删除记录
    let record_id = objects[0]._id
    await caseCollectionTabel.delete(record_id)
    return { code: 0, message: "取消收藏成功" }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

// 获取所有收藏药膳
async function getCollectCaseList<T>(page: number = 1, pageSize: number = 10, user_id: string): ResponsePromiseData<T> {
  try {
    // 先获取所有收藏的药膳id
    let query: any = new minappSdk.Query()
    query.contains("user_id", user_id)
    const {
      data: { objects }
    } = await caseCollectionTabel.setQuery(query).find()
    let collectedIds = objects.map((item: any) => item.case_id)
    console.log(collectedIds, collectedIds)
    let results: any[] = []
    for (let caseId of collectedIds) {
      let { data } = await oralCaseTabel.get(caseId)
      results.push(data)
    }
    // 手动分页
    const offset: number = (page - 1) * pageSize

    // 获取药膳
    return {
      code: 0,
      message: `获取成功`,
      data: {
        list: results.slice(offset, offset + pageSize),
        total: results.length
      } as T
    }
  } catch (error: any) {
    message.error(error.message)
    return Promise.reject(error.message)
  }
}

export default {
  getAllCaseCategory,
  getCaseCategoryList,
  addCaseCategory,
  getCaseCategoryInfo,
  updateCateCategory,
  deleteCaseCategory,

  getCaseRecords,
  getCaseInfo,
  addCaseRecord,
  updateCaseRecord,
  deleteCaseRecord,
  getTodayCaseCount,
  collectCase,
  unCollectCase,
  getCollectCaseList
}
